<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElButton, ElMessage, ElRadio, ElRadioGroup, ElInput, ElForm, ElFormItem, ElDialog } from 'element-plus'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { addressInfoService, addressAddService, addressUpdateService, addressDeleteService, addressDefaultService } from '@/api/address.js'
import { createOrderService } from '@/api/order.js'

const router = useRouter()
const route = useRoute()
import useUserInfoStore from '@/stores/userInfo.js'
const userInfoStore = useUserInfoStore()

// 从路由参数获取订单商品数据
const orderItems = ref([])

// 初始化订单商品数据
const initOrderItems = () => {
  try {
    const itemsParam = route.query.items
    if (itemsParam) {
      const items = JSON.parse(itemsParam)
      orderItems.value = items.map(item => ({
        id: item.id,
        productId: item.productId,
        name: item.name,
        price: parseFloat(item.price),
        originalPrice: parseFloat(item.originalPrice || item.price),
        image: item.image,
        quantity: parseInt(item.quantity),
        specs: item.specs 
      }))
      console.log('购物车传过来的商品信息:', orderItems.value)
    } else {
      // 如果没有传递商品数据，跳转回购物车
      ElMessage.warning('请从购物车选择商品进行结算')
      router.push('/home/cart')
    }
  } catch (error) {
    console.error('解析订单商品数据失败:', error)
    ElMessage.error('订单数据解析失败，请重新选择商品')
    router.push('/home/cart')
  }
}

// 收货地址列表
const addressList = ref([])

// 获取地址列表
const getAddressList = async () => {
  const result = await addressInfoService(userInfoStore.info.id)
  addressList.value = result
  // 设置默认选中的地址
  const defaultAddress = addressList.value.find(addr => addr.isDefault)
  if (defaultAddress) {
    selectedAddress.value = defaultAddress.id
  } else if (addressList.value.length > 0) {
    selectedAddress.value = addressList.value[0].id
  }
}

// 选中的地址
const selectedAddress = ref(addressList.value.find(addr => addr.isDefault)?.id || null)

// 新增地址表单
const showAddressDialog = ref(false)
const isEdit = ref(false)
const newAddress = ref({
  contact: '',
  phone: '',
  province: '',
  city: '',
  town: '',
  street: '',
  notes: '',
  isDefault: false
})

// 支付方式
const paymentMethod = ref('balance')

// 计算总价
const totalPrice = computed(() => {
  return orderItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 计算运费
const shippingFee = computed(() => {
  return totalPrice.value >= 99 ? 0 : 10
})

// 计算最终价格
const finalPrice = computed(() => {
  return totalPrice.value + shippingFee.value
})

// 获取选中的地址信息
const getSelectedAddress = computed(() => {
  return addressList.value.find(addr => addr.id === selectedAddress.value)
})

// 设置默认地址
const setDefaultAddress = async (addressId) => {
  try {
    await addressDefaultService(addressId)
    ElMessage.success('设置默认地址成功')
    await getAddressList() 
  } catch (error) {
    ElMessage.error('设置默认地址失败')
  }
}

// 删除地址
const deleteAddress = async (addressId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await addressDeleteService(addressId)
    ElMessage.success('删除地址成功')
    await getAddressList() 
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除地址失败')
    }
  }
}

// 编辑地址
const editAddress = (address) => {
  isEdit.value = true
  currentEditAddress.value = address
  showAddAddressForm.value = true
  
  // 填充表单数据
  newAddress.value = {
    id: address.id,
    contact: address.contact,
    phone: address.phone || '',
    province: address.province,
    city: address.city,
    town: address.town,
    street: address.street,
    notes: address.notes || '',
    isDefault: address.isDefault
  }
}

// 打开新增地址弹窗
const handleAddAddress = () => {
  isEdit.value = false
  resetAddressForm()
  showAddressDialog.value = true
}

// 重置表单
const resetAddressForm = () => {
  newAddress.value = {
    contact: '',
    phone: '',
    province: '',
    city: '',
    town: '',
    street: '',
    notes: '',
    isDefault: false
  }
}

// 保存地址（新增或编辑）
const saveNewAddress = async () => {
  // 表单校验
  if (!newAddress.value.contact.trim()) {
    ElMessage.error('请输入收货人姓名')
    return
  }
  if (!newAddress.value.phone.trim() || !/^1[3-9]\d{9}$/.test(newAddress.value.phone)) {
    ElMessage.error('请输入有效的手机号码')
    return
  }
  if (!newAddress.value.province.trim() || !newAddress.value.city.trim() || !newAddress.value.town.trim()) {
    ElMessage.error('请完善所在地区')
    return
  }
  if (!newAddress.value.street.trim()) {
    ElMessage.error('请输入详细地址')
    return
  }

  try {
    const addressData = {
      ...newAddress.value,
      userId: userInfoStore.info.id
    }
    if (isEdit.value) {
      await addressUpdateService(addressData)
      ElMessage.success('地址更新成功')
    } else {
      await addressAddService(addressData)
      ElMessage.success('地址添加成功')
    }
    showAddressDialog.value = false
    resetAddressForm()
    await getAddressList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '地址更新失败' : '地址添加失败')
  }
}

// 提交订单
const handleSubmitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  if (orderItems.value.length === 0) {
    ElMessage.warning('订单商品为空')
    return
  }
  // 组装后端需要的CartItemDTO结构
  const orderItemDTOList = orderItems.value.map(item => ({
    productId: Number(item.productId),
    name: item.name,
    productPic: item.image,
    specs: JSON.stringify(item.specs),
    productQuantity: Number(item.quantity),
    productPrice: Math.round(Number(item.price))
  }))
  const orderData = {
    addressId: Number(selectedAddress.value),
    paymentType: 3, // 余额支付
    totalPrice: Number(finalPrice.value),
    orderItemDTOList
  }
  try {
    console.log("订单数据",orderData)
    const result= await createOrderService(orderData)
    const orderInfo = result.data
    ElMessage.success('订单提交成功！')
    setTimeout(() => {
      router.push({
        path: '/home/order/success',
        query: {
          orderNo: orderInfo.orderNumber,
          paymentAmount: orderInfo.totalPrice ? Number(orderInfo.totalPrice) : 0,
          paymentMethod: orderInfo.payType,
          paymentTime: orderInfo.payTime,
          estimatedDelivery: orderInfo.msg
        }
      })
    }, 500)
  } catch (e) {
    ElMessage.error('订单提交失败，请稍后重试')
  }
}

// 返回购物车
const goBackToCart = () => {
  router.push('/home/cart')
}

// 处理支付方式变更
const handlePaymentMethodChange = (value) => {
  if (value !== 'balance') {
    ElMessage.warning('目前只支持余额支付')
    paymentMethod.value = 'balance'
  }
}

onMounted(() => { 
  initOrderItems()
  getAddressList()
})
</script>

<template>
  <CommonHeader />
  <FloatingSidebar />
  <div class="order-confirm-page">
    <div class="container">
      <h1 class="page-title">确认订单</h1>

      <!-- 收货地址 -->
      <div class="section address-section">
        <div class="section-header">
          <h2 class="section-title">收货地址</h2>
          <el-button type="primary" link @click="handleAddAddress">+ 新增收货地址</el-button>
        </div>
        
        <div class="address-list">
          <div
            v-for="address in addressList"
            :key="address.id"
            class="address-item"
            :class="{ active: selectedAddress === address.id }"
            @click="selectedAddress = address.id"
          >
            <div class="address-content">
              <div class="address-info">
                <span class="name">{{ address.contact }}</span>
                <span class="phone">{{ address.phone || '暂无手机号' }}</span>
                <span v-if="address.isDefault" class="default-tag">默认</span>
              </div>
              <div class="address-detail">
                {{ address.province }}{{ address.city }}{{ address.town }}{{ address.street }}
              </div>
            </div>
            <div class="address-actions">
              <el-button type="primary" link @click.stop="setDefaultAddress(address.id)">
                {{ address.isDefault ? '默认地址' : '设为默认' }}
              </el-button>
              <el-button type="danger" link @click.stop="deleteAddress(address.id)">删除</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="section items-section">
        <h2 class="section-title">商品清单</h2>
        <div class="order-items">
          <div v-for="item in orderItems" :key="item.id" class="order-item">
            <el-image :src="item.image" fit="cover" class="item-image" />
            <div class="item-info">
              <h3 class="item-name">{{ item.name }}</h3>
              <div class="item-price">
                <span class="current-price">¥{{ item.price.toFixed(2) }}</span>
                <span v-if="item.originalPrice && item.originalPrice > item.price" class="original-price">
                  ¥{{ item.originalPrice.toFixed(2) }}
                </span>
              </div>
            </div>
            <div class="item-quantity">x{{ item.quantity }}</div>
            <div class="item-subtotal">
              <div class="subtotal-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              <div v-if="item.originalPrice && item.originalPrice > item.price" class="saved-amount">
                节省: ¥{{ ((item.originalPrice - item.price) * item.quantity).toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section payment-section">
        <h2 class="section-title">支付方式</h2>
        <el-radio-group v-model="paymentMethod" @change="handlePaymentMethodChange">
          <el-radio label="balance">余额支付</el-radio>
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
          <el-radio label="card">银行卡</el-radio>
        </el-radio-group>
      </div>

      <!-- 订单金额 -->
      <div class="section price-section">
        <h2 class="section-title">订单金额</h2>
        <div class="price-details">
          <div class="price-item">
            <span>商品总额</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="price-item">
            <span>运费</span>
            <span>{{ shippingFee === 0 ? '免运费' : `¥${shippingFee.toFixed(2)}` }}</span>
          </div>
          <div class="price-item total">
            <span>应付总额</span>
            <span class="final-price">¥{{ finalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="order-actions">
        <el-button @click="goBackToCart">返回购物车</el-button>
        <el-button type="primary" size="large" @click="handleSubmitOrder">
          提交订单
        </el-button>
      </div>
    </div>
  </div>

  <!-- 新增地址对话框 -->
  <el-dialog
    v-model="showAddressDialog"
    title="新增收货地址"
    width="500px"
  >
    <el-form :model="newAddress" label-width="80px">
      <el-form-item label="收货人">
        <el-input v-model="newAddress.contact" placeholder="请输入收货人姓名" />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="newAddress.phone" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="所在地区">
        <div class="address-region">
          <el-input v-model="newAddress.province" placeholder="省" />
          <el-input v-model="newAddress.city" placeholder="市" />
          <el-input v-model="newAddress.town" placeholder="区" />
        </div>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input
          v-model="newAddress.street"
          type="textarea"
          placeholder="请输入详细地址"
          :rows="2"
        />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="newAddress.isDefault">设为默认收货地址</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="saveNewAddress">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <CommonFooter />
</template>

<style scoped>
.order-confirm-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 20px;
  text-align: center;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.address-item {
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
}

.address-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.address-content {
  margin-bottom: 10px;
}

.address-info {
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-right: 10px;
}

.phone {
  color: #606266;
}

.default-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #409eff;
  color: white;
  border-radius: 2px;
  font-size: 12px;
  margin-left: 10px;
}

.address-detail {
  color: #606266;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.address-region {
  display: flex;
  gap: 10px;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
}

.item-info {
  flex-grow: 1;
}

.item-name {
  font-size: 16px;
  color: #303133;
  margin: 0 0 8px 0;
}

.item-price {
  font-size: 16px;
  color: #909399;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 8px;
}

.original-price {
  color: #c0c4cc;
  text-decoration: line-through;
  font-size: 14px;
}

.item-quantity {
  color: #909399;
  margin: 0 20px;
}

.item-subtotal {
  min-width: 120px;
  text-align: right;
}

.subtotal-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.saved-amount {
  font-size: 12px;
  color: #67c23a;
  margin-top: 4px;
}

.price-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.price-item.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  font-size: 18px;
  color: #303133;
}

.final-price {
  color: #f56c6c;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .address-region {
    flex-direction: column;
  }
  
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .order-item {
    flex-wrap: wrap;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
  
  .item-quantity {
    margin: 10px 0;
  }
  
  .item-subtotal {
    width: 100%;
    text-align: right;
  }
  
  .order-actions {
    flex-direction: column;
  }
  
  .order-actions .el-button {
    width: 100%;
  }
}
</style> 